<!DOCTYPE html>
<html>
<head>
    

    

    



    <meta charset="utf-8">
    
    
    
    
    <title>NodeJS中的CommonJS规范 | Anson&#39;s Blog | 种一棵树最好的时间在十年前，其次是现在。</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#3F51B5">
    
    
    <meta name="keywords" content="NodeJS">
    <meta name="description" content="模块化的意义 在计算机程序的开发过程中，随着程序代码越写越多，在一个文件里代码就会越来越长，越来越不容易维护。为了编写可维护的代码，我们把很多函数分组，分别放到不同的文件里，这样，每个文件包含的代码就相对较少，很多编程语言都采用这种组织代码的方式。在Node环境中，一个.js文件就称之为一个模块（module）。  理解模块化最大的好处是大大提高了代码的可维护性。其次，编写代码不必从零开始。当一个">
<meta name="keywords" content="NodeJS">
<meta property="og:type" content="article">
<meta property="og:title" content="NodeJS中的CommonJS规范">
<meta property="og:url" content="http://yoursite.com/2018/10/18/CommonJS模块化开发/index.html">
<meta property="og:site_name" content="Anson&#39;s Blog">
<meta property="og:description" content="模块化的意义 在计算机程序的开发过程中，随着程序代码越写越多，在一个文件里代码就会越来越长，越来越不容易维护。为了编写可维护的代码，我们把很多函数分组，分别放到不同的文件里，这样，每个文件包含的代码就相对较少，很多编程语言都采用这种组织代码的方式。在Node环境中，一个.js文件就称之为一个模块（module）。  理解模块化最大的好处是大大提高了代码的可维护性。其次，编写代码不必从零开始。当一个">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/7072486-0d6620b0e8d69fa6.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/7072486-d7e8e14a1da2526b.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2018-12-21T08:24:19.287Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="NodeJS中的CommonJS规范">
<meta name="twitter:description" content="模块化的意义 在计算机程序的开发过程中，随着程序代码越写越多，在一个文件里代码就会越来越长，越来越不容易维护。为了编写可维护的代码，我们把很多函数分组，分别放到不同的文件里，这样，每个文件包含的代码就相对较少，很多编程语言都采用这种组织代码的方式。在Node环境中，一个.js文件就称之为一个模块（module）。  理解模块化最大的好处是大大提高了代码的可维护性。其次，编写代码不必从零开始。当一个">
<meta name="twitter:image" content="https://upload-images.jianshu.io/upload_images/7072486-0d6620b0e8d69fa6.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
    
        <link rel="alternate" type="application/atom+xml" title="Anson&#39;s Blog" href="/atom.xml">
    
    <link rel="shortcut icon" href="/img/favicon.ico">
    <link rel="stylesheet" href="//unpkg.com/hexo-theme-material-indigo@latest/css/style.css">
    <script>window.lazyScripts=[]</script>

    <!-- custom head -->
    

</head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu"  >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap" style="background-image:url(/img/brand.jpg)">
      <div class="brand">
        <a href="/" class="avatar waves-effect waves-circle waves-light">
          <img src="https://yscoder.github.io/img/face.jpg">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">张宁乐</h5>
          <a href="mailto:zhangningle2017@gmail.com" title="zhangningle2017@gmail.com" class="mail">zhangningle2017@gmail.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/"  >
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/archives"  >
                <i class="icon icon-lg icon-archives"></i>
                归档
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                标签
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/about"  >
                <i class="icon icon-lg icon-user"></i>
                关于
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://github.com/ansonznl" target="_blank" >
                <i class="icon icon-lg icon-github"></i>
                Github
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">NodeJS中的CommonJS规范</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">NodeJS中的CommonJS规范</h1>
        <h5 class="subtitle">
            
                <time datetime="2018-10-18T06:04:55.000Z" itemprop="datePublished" class="page-time">
  2018-10-18
</time>


            
        </h5>
    </div>

    


</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap post-toc-shrink" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#模块化的意义"><span class="post-toc-number">1.</span> <span class="post-toc-text">模块化的意义</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#理解模块化"><span class="post-toc-number">2.</span> <span class="post-toc-text">理解模块化</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#CommonJS案例"><span class="post-toc-number">3.</span> <span class="post-toc-text">CommonJS案例</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#案例：写一个求和-求平均数的模块"><span class="post-toc-number">4.</span> <span class="post-toc-text">案例：写一个求和 / 求平均数的模块</span></a></li></ol>
        </nav>
    </aside>


<article id="post-CommonJS模块化开发"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">NodeJS中的CommonJS规范</h1>
        <div class="post-meta">
            <time class="post-time" title="2018-10-18 14:04:55" datetime="2018-10-18T06:04:55.000Z"  itemprop="datePublished">
2018-10-18
<!--2018-12-21 16:24:19-->
</time>

            


            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style='display:none'>
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <h3 id="模块化的意义"><a href="#模块化的意义" class="headerlink" title="模块化的意义"></a>模块化的意义</h3><blockquote>
<p>在计算机程序的开发过程中，随着程序代码越写越多，在一个文件里代码就会越来越长，越来越不容易维护。<br>为了编写可维护的代码，我们把很多函数分组，分别放到不同的文件里，这样，每个文件包含的代码就相对较少，很多编程语言都采用这种组织代码的方式。在Node环境中，一个.js文件就称之为一个模块（module）。</p>
</blockquote>
<h3 id="理解模块化"><a href="#理解模块化" class="headerlink" title="理解模块化"></a>理解模块化</h3><p>最大的好处是大大提高了代码的可维护性。其次，编写代码不必从零开始。当一个模块编写完毕，就可以被其他地方引用。我们在编写程序的时候，也经常引用其他模块，包括Node内置的模块和来自第三方的模块。<br>使用模块还可以避免函数名和变量名冲突。相同名字的函数和变量完全可以分别存在不同的模块中，因此，我们自己在编写模块时，不必考虑名字会与其他模块冲突。</p>
<p><strong>每一个文件都可以看成一个模块，模块都可以相互暴露和相互引用</strong><br>1.在Node中 一个文件就是一个模块<br>2.在Node中，通过require()函数来引入外部的模块，引入外部模块要加上 ./ 或者 ../<br>3.在Node中，每一个js文件中js代码都是独立运行在一个小闭包中，而不是全局作用域，所以一个模块在不引用的情况下它的的变量和函数都在其他模块中无法访问，如果引用到其他模块中，则被引用的文件相当与在一个闭包内，相当与局部变量。<br>目的：全局变量私有化，避免全局污染。<br>4.暴露模块中的变量和函数：使用exports<br>只需要将需要暴露给外部的变量或者方法设置为exports的属性就行，<br><strong>可以把exports看做一个全局对象，把所有暴露出来的函数和变量都存放在里面</strong><br>Node有一些自带的模块，成为核心模块，他的引用不需要加./ 或者../ 如fs http</p>
<p><img src="https://upload-images.jianshu.io/upload_images/7072486-0d6620b0e8d69fa6.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="171539764614_.pic.jpg"></p>
<p>引用：<code>const  moudel = require (&#39;./02.js&#39;)</code><br>暴露：<code>exports.str = srt;</code></p>
<h3 id="CommonJS案例"><a href="#CommonJS案例" class="headerlink" title="CommonJS案例"></a>CommonJS案例</h3><p>先写一个01.js暴露出去：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">let str = &quot;我是小二&quot;;</span><br><span class="line"></span><br><span class="line">let test = ()=&gt;&#123;</span><br><span class="line">  console.log(&quot;今天天气很好!&quot;);</span><br><span class="line">&#125;</span><br><span class="line">exports.str = str;</span><br><span class="line">exports.test = test;</span><br></pre></td></tr></table></figure></p>
<p>在写一个02.js把暴露的01.js引用过来, 然后暴露自身<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">const module02 = require(&apos;./01.js&apos;);// [ ./  ../ ]</span><br><span class="line"></span><br><span class="line">exports.module02 = module02; //暴露</span><br><span class="line"></span><br><span class="line">console.log(module02.str);//我是小二</span><br></pre></td></tr></table></figure></p>
<p>最后在写一个03.js 引用暴露的02.js， 这样在03.js 里就包含了 02.js 和01.js了：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">const module03 = require(&apos;./02.js&apos;);</span><br><span class="line">console.log(module03.module02.str)//我是小二</span><br></pre></td></tr></table></figure></p>
<p>所以最后是这样的：<br><figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="https://upload-images.jianshu.io/upload_images/7072486-d7e8e14a1da2526b.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="161539764109_.pic.jpg" title="">
                </div>
                <div class="image-caption">161539764109_.pic.jpg</div>
            </figure></p>
<p>类似一个同心圆</p>
<h3 id="案例：写一个求和-求平均数的模块"><a href="#案例：写一个求和-求平均数的模块" class="headerlink" title="案例：写一个求和 / 求平均数的模块"></a>案例：写一个求和 / 求平均数的模块</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">exports.sun = (...numbers)=&gt;&#123;</span><br><span class="line">    let result = 0;</span><br><span class="line">    numbers.forEach((itme)=&gt;&#123;</span><br><span class="line">        result += itme;</span><br><span class="line">    &#125;);</span><br><span class="line">    return result;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">exports.avg= (...numbers)=&gt;&#123;</span><br><span class="line">    let result = 0;</span><br><span class="line">    numbers.forEach((itme)=&gt;&#123;</span><br><span class="line">        result+= itme;</span><br><span class="line">    &#125;);</span><br><span class="line">    return result / numbers.length;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>参考资料：<a href="https://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000/001434502419592fd80bbb0613a42118ccab9435af408fd000" target="_blank" rel="noopener">廖雪峰的官网-模块开发</a><br>视频资料：<a href="https://study.163.com/course/courseLearn.htm?courseId=1005269026#/learn/video?lessonId=1052250610&amp;courseId=1005269026" target="_blank" rel="noopener">网易云课堂-叶建秋-从零玩转Node.js</a></p>

        </div>

        <blockquote class="post-copyright">
    
    <footer>
        <a href="http://yoursite.com">
            <img src="https://yscoder.github.io/img/face.jpg" alt="张宁乐">
            张宁乐
        </a>
    </footer>
</blockquote>

        


        <div class="post-footer">
            
	<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/NodeJS/">NodeJS</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://yoursite.com/2018/10/18/CommonJS模块化开发/&title=《NodeJS中的CommonJS规范》 — Anson's Blog&pic=https://yscoder.github.io/img/face.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://yoursite.com/2018/10/18/CommonJS模块化开发/&title=《NodeJS中的CommonJS规范》 — Anson's Blog&source=张宁乐,博客" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://yoursite.com/2018/10/18/CommonJS模块化开发/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《NodeJS中的CommonJS规范》 — Anson's Blog&url=http://yoursite.com/2018/10/18/CommonJS模块化开发/&via=http://yoursite.com" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://yoursite.com/2018/10/18/CommonJS模块化开发/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/2018/11/05/Node中的Buffer/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">NodeJS中的Buffer</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/2018/10/11/NodeJS安装和使用/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">NodeJS安装和使用</h4>
      </a>
    </div>
  
</nav>



    











    <!-- Valine Comments -->
    <div class="comments vcomment" id="comments"></div>
    <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
    <script src="//unpkg.com/valine@latest/dist/Valine.min.js"></script>
    <!-- Valine Comments script -->
    <script>
        var GUEST_INFO = ['nick','mail','link'];
        var guest_info = 'nick,mail'.split(',').filter(function(item){
          return GUEST_INFO.indexOf(item) > -1
        });
        new Valine({
            el: '#comments',
            notify: 'false' == 'true',
            verify: 'false' == 'true',
            appId: "gbSwUaucLkuxqOLxm131Mg9U-gzGzoHsz",
            appKey: "b9xU2qIPrm06S0uymbAfrGMD",
            avatar: "mm",
            placeholder: "要不要说点什么？",
            guest_info: guest_info.length == 0 ? GUEST_INFO : guest_info,
            pageSize: "10"
        })
    </script>
    <!-- Valine Comments end -->







</article>



</div>

        <footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        站点总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        站点总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            
                <span><a href="/atom.xml" target="_blank" class="rss" title="rss"><i class="icon icon-lg icon-rss"></i></a></span>
            
            <span>博客内容遵循 <a rel="license" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">知识共享 署名 - 非商业性 - 相同方式共享 4.0 国际协议</a></span>
        </p>
    </div>
    <div class="bottom">
        <p><span>张宁乐 &copy; 2017 - 2019</span>
            <span>
                
                Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://github.com/yscoder/hexo-theme-indigo" target="_blank">indigo</a>
            </span>
			<span>
					Hosted by <a href="https://pages.coding.me" style="font-weight: bold">Coding Pages</a>
			  </span>
        </p>
    </div>
</footer>
<!-- <script>
(function(){
    var bp = document.createElement("script");
    var curProtocol = window.location.protocol.split(":")[0];
    if (curProtocol === "https") {
        bp.src = "https://zz.bdstatic.com/linksubmit/push.js";
    }
    else {
        bp.src = "http://push.zhanzhang.baidu.com/push.js";
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script> -->

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://yoursite.com/2018/10/18/CommonJS模块化开发/&title=《NodeJS中的CommonJS规范》 — Anson's Blog&pic=https://yscoder.github.io/img/face.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://yoursite.com/2018/10/18/CommonJS模块化开发/&title=《NodeJS中的CommonJS规范》 — Anson's Blog&source=张宁乐,博客" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://yoursite.com/2018/10/18/CommonJS模块化开发/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《NodeJS中的CommonJS规范》 — Anson's Blog&url=http://yoursite.com/2018/10/18/CommonJS模块化开发/&via=http://yoursite.com" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://yoursite.com/2018/10/18/CommonJS模块化开发/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/', SHARE: true, REWARD: false };


</script>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/main.min.js"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/search.min.js" async></script>






<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>





</body>
</html>
